package com.ang.juc.n4.t1;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Test1_1 {
    private static final Logger log = LoggerFactory.getLogger(Test1_1.class);
    Object lock = new Object();

    public volatile boolean flag = false;

    class Task1 implements Runnable {
        public void run() {
            synchronized (lock) {
                while (true) {
                    if (flag) {
                        System.out.println(Thread.currentThread().getName() + " is running...");
                        flag = !flag;
                        lock.notify();
                    } else {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        }
    }

    class Task2 implements Runnable {
        public void run() {
            synchronized (lock) {
                while (true) {
                    if (!flag) {
                        System.out.println(Thread.currentThread().getName() + " is running...");
                        flag = !flag;
                        lock.notify();
                    } else {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        }
    }

    public void test1() throws Exception {
        Thread t1 = new Thread(new Task1(), "线程1");
        Thread t2 = new Thread(new Task2(), "线程2");
        t1.start();
        t2.start();
    }

    //=====================================
    public static void main(String[] args) throws Exception {
        System.out.println("rice-----------------------");
        Test1_1 test11 = new Test1_1();
        test11.test1();
    }

}
